/*
 * @Author: Hp_lucky 1063512385@qq.com
 * @Date: 2024-09-28 14:34:52
 * @LastEditors: Hp_lucky 1063512385@qq.com
 * @LastEditTime: 2024-10-14 11:52:04
 * @FilePath: \lucky-rpg\assets\script\src\Basic\Model\Effect\EffectAnimation.ts
 */
import { _decorator, AnimationClip, Animation } from 'cc';
import { Effect } from './Effect';
const { ccclass, property } = _decorator;

@ccclass('EffectAnimation')
export class EffectAnimation extends Effect {
  @property(Animation)
  private ani: Animation = null!;

  protected onLoad(): void {
    this.ani.on(Animation.EventType.FINISHED, this.playEnd, this);
  }

  protected onEnable(): void {
    if (this.effParam == '') return;
    const state = this.ani.getState(this.effParam);
    if (this.loop < 0) {
      state.clip.wrapMode = AnimationClip.WrapMode.Loop;
      state.repeatCount = Infinity;
    } else {
      state.clip.wrapMode = AnimationClip.WrapMode.Default;
      state.repeatCount = this.loop;
    }
    if (this.param) {
      if (this.param.position) {
        this.node.setPosition(this.param.position);
      } else {
        this.node.setPosition(this.param.x ?? 0, this.param.y ?? 0);
      }
    }
    this.ani.stop();
    this.ani.defaultClip = null;
    this.ani.play(this.effParam);
  }

  private playEnd() {
    this.loop--;
    if (this.loop == 0) {
      this.unuse();
    }
  }

  unuse() {
    this.ani.stop();
    this.ani.defaultClip = null;
    this.ani.off(Animation.EventType.FINISHED, this.playEnd, this);
    this.ani.on(Animation.EventType.FINISHED, this.playEnd, this);
    super.unuse();
  }
}
